<?php
namespace app\controller;


use app\common\model\CommentModel;
use app\common\model\CouponUserModel;
use app\common\model\GoodsModel;
use app\common\model\OrderModel;
use app\common\model\PlatformFreightPlanModel;
use app\common\model\PlatformNotifyModel;
use app\common\model\SysSettingModel;
use app\common\model\UserAddrModel;
use app\common\model\UserCartModel;
use app\common\service\Config;
use app\common\service\Paypal;

class Order extends Common
{
    public function lists()
    {
        $input_data = input();
        $input_data['status'] = 1;
        $input_data['check_type'] = 0;
        $input_data['user_id'] = $this->user_id;

        $list = [];
        $info = OrderModel::getPageData($input_data)->each(function($item) use (&$list){
            array_push($list,$item->apiNormalInfo());
        });
        $count_where = [];
        $count_where[] = ['uid','=',$this->user_id];
        return $this->_resData(1,'获取成功',[
            'list'=>$list,
            'total'=>$info->total(),
            'wait_pay_total'=>empty($count_where)?0:OrderModel::where($count_where)->where(OrderModel::getStateWhere('wait_pay')[0])->count(),
            'send_total'=>empty($count_where)?0:OrderModel::where($count_where)->where(OrderModel::getStateWhere('send')[0])->count(),
            'wait_rec_total'=>empty($count_where)?0:OrderModel::where($count_where)->where(OrderModel::getStateWhere('wait_rec')[0])->count(),
            'complete_total'=>empty($count_where)?0:OrderModel::where($count_where)->where(OrderModel::getStateWhere('completed')[0])->count(),
            'refund_total'=>empty($count_where)?0:OrderModel::where($count_where)->where(OrderModel::getStateWhere('refund')[1])->count(),
            'total_page'=>$info->lastPage(),
        ]);
    }

    public function detail()
    {
        $order_id = input('order_id');
        $input_data['status'] = 1;
        $input_data['check_type'] = 0;
        $input_data['user_id'] = $this->user_id;
        $input_data['id'] = $order_id;

        $orderModel = [];
        OrderModel::getPageData($input_data)->each(function($item) use (&$orderModel){
            $orderModel = $item;
        });
        list($status_name,$handle_action) = empty($orderModel)?["",[]]:$orderModel->getStatusName();
        return view('detail',[
            'orderModel'=>$orderModel,
            'status_name'=>$status_name,
            'handle_action' => $handle_action,
        ]);
    }

    public function freightList()
    {
        $freightList = PlatformFreightPlanModel::getFreightList(input('country'),input('goods_money'),input('goods_weight'));

        return $this->_resData(1,lang('tip_get_success'),[
            'freight_list'=>$freightList,
        ]);
    }


    public function preview()
    {
        $express_money = SysSettingModel::getContent('free','express_money');
        $tip_list = SysSettingModel::getContent('free','tip_per_intro_shape');
        $express_list = SysSettingModel::getContent('free','express_money_intro_shape');
        $address_list = [];
        if(!empty($this->user_id)){
            UserAddrModel::getPageData(['uid'=>$this->user_id,'status'=>1])->each(function($item) use (&$address_list){
                array_push($address_list,$item->apiNormalInfo());
            });
        }


        return view('preview',[
            'express_money'=>empty($express_money) ? 0 : $express_money,
            'tip_list'=>empty($tip_list) ? [] : $tip_list,
            'express_list'=>empty($express_list) ? [] : $express_list,
            'address_list'=>empty($address_list) ? [] : $address_list,
        ]);
    }

    public function confirm()
    {
        try {
            $input_data = input();
            $input_data['uid'] = $this->user_id;
            $input_data['session_id'] = $this->session_id;
            $order_model = OrderModel::confirm($this->user_model, $input_data);

            $data = [];
            if(empty($order_model['is_pay'])){
                $data = OrderModel::getOrderPayInfo($order_model,$input_data['pay_way'],$input_data);
            }else{
                $data['url'] = url('/user/order',['order_id'=>$order_model['id']])->build();
            }

        } catch (\Exception $e) {
            return $this->_resData(0, $e->getMessage());
        }

        return $this->_resData(1, lang('tip_order_success'), array_merge($data,[
            'num' => UserCartModel::getNum($this->user_id,$this->session_id),
        ]));
    }

    public function payInfo()
    {
        $input_data = input();
        $input_data['uid'] = $this->user_id;
        $input_data['session_id'] = $this->session_id;
        $order_id = input('order_id');
        $pay_way = input('pay_way');
        try {
            $order_model = OrderModel::find($order_id);
            if(empty($order_model)) throw new \Exception(lang('err_order_no_exist'));
            $data = OrderModel::getOrderPayInfo($order_model, $pay_way,$input_data);
        } catch (\Exception $e) {
            return $this->_resData(0, $e->getMessage());
        }

        return $this->_resData(1, lang('tip_get_success'), $data);
    }

    public function paypalCheckDetail()
    {
        $order_id = input('order_id');
        $paymentId = input('paymentId');
        $token = input('token');
        $PayerID = input('PayerID');
        if(!empty($order_id)){
            $model_order = OrderModel::find($order_id);
            if(!empty($model_order)){
                try{
                    $paypal_orderid = $model_order['paypal_orderid'];
                    $paypal_result = Paypal::checkout_order_detail($paypal_orderid);
                    PlatformNotifyModel::record('paypal',OrderModel::class,$order_id,$model_order['no'],$paypal_result);
//                    dump($model_order,$paypal_orderid,$paypal_result);exit;

                }catch (\Exception $e){
                    echo $e->getMessage();exit;
                }
            }


        }

        return redirect(url('user/order',input()));
    }

    //删除订单
    public function del()
    {

        $id =  input('id');
        try{
            OrderModel::del($this->user_model,$id);
            return $this->_resData(1,'操作成功');
        }catch (\Exception $e){
            return $this->_resData(0,$e->getMessage());
        }
    }

    //取消订单
    public function cancel()
    {

        $id = $this->request->param('id');
        try{
            $model = OrderModel::cancel($this->user_model,$id);
        }catch (\Exception $e){
            return $this->_resData(0,$e->getMessage());
        }
        list($status_name,$handle_action) = $model->getStatusName();
        return $this->_resData(1,lang('tip_opt_success'),[
            'status'=> (int)$model['status'],
            'status_name' => $status_name,
            'handle_action' => $handle_action,
        ]);
    }
    //确认收货
    public function receive()
    {

        $id = $this->request->param('id');
        try{
            $model = OrderModel::receive($this->user_model,$id);
        }catch (\Exception $e){
            return $this->_resData(0,$e->getMessage());
        }
        list($status_name,$handle_action) = $model->getStatusName();
        return $this->_resData(1,lang('tip_opt_success'),[
            'status'=> (int)$model['status'],
            'status_name' => $status_name,
            'handle_action' => $handle_action,
        ]);
    }
}